package ay.shadow.security.handler;

import ay.shadow.core.utils.JwtTokenProvider;
import org.springframework.security.authentication.ReactiveAuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;
import reactor.core.publisher.Mono;

import java.util.Collection;
import java.util.List;

@Component
public class CustomReactiveAuthManager implements ReactiveAuthenticationManager {

    /**
     * 自定义认证逻辑：验证JWT令牌
     *
     * @param authentication 包含待验证的令牌信息
     * @return 验证通过的Authentication（已认证状态）
     */
    @Override
    public Mono<Authentication> authenticate(Authentication authentication) {
        // 从Authentication中获取令牌（假设存储在credentials中）
        String token = (String) authentication.getCredentials();

        try {
            // 1. 从令牌解析用户名
            String username = JwtTokenProvider.getUsernameFromToken(token);
            String role = JwtTokenProvider.getRoleFromToken(token);
            String password = JwtTokenProvider.getRoleFromToken(token);
            // 2. 查询用户信息并验证令牌
            // 3. 验证令牌有效性
            if (JwtTokenProvider.validateToken(token, username)) {
                UserDetails userDetails = new UserDetails() {
                    @Override
                    public Collection<? extends GrantedAuthority> getAuthorities() {
                        return List.of(new SimpleGrantedAuthority(role));
                    }

                    @Override
                    public String getPassword() {
                        return password;
                    }

                    @Override
                    public String getUsername() {
                        return username;
                    }

                    @Override
                    public boolean isAccountNonExpired() {
                        return false;
                    }

                    @Override
                    public boolean isAccountNonLocked() {
                        return false;
                    }

                    @Override
                    public boolean isCredentialsNonExpired() {
                        return false;
                    }

                    @Override
                    public boolean isEnabled() {
                        return true;
                    }
                };
                UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(
                        userDetails,  // 身份信息
                        token,        // 凭证（令牌）
                        userDetails.getAuthorities()// 权限
                );

                SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken);
                // 4. 认证成功：构建已认证的Authentication对象
                return Mono.just(usernamePasswordAuthenticationToken);
            } else {
                // 令牌无效
                return Mono.error(new IllegalArgumentException("无效的令牌"));
            }
        } catch (Exception e) {
            // 令牌解析失败（如过期、格式错误）
            return Mono.error(new IllegalArgumentException("令牌解析失败：" + e.getMessage()));
        }
    }
}
